<template>
  <div class="employees-detail-container">
    <div class="app-container">
      <el-card>
        <!-- 放置表单 -->
        <el-form
          ref="userForm"
          label-width="120px"
          style="margin-left: 120px; margin-top: 30px"
          :model="userInfo"
          :rules="rules"
        >
          <el-form-item label="姓名:" prop="username">
            <el-input v-model="userInfo.username" style="width: 300px" />
          </el-form-item>
          <el-form-item label="手机">
            <el-input v-model="userInfo.mobile" style="width: 300px" disabled />
          </el-form-item>
          <el-form-item label="入职时间" prop="timeOfEntry">
            <el-date-picker
              v-model="userInfo.timeOfEntry"
              type="date"
              class="inputW"
            />
          </el-form-item>
          <el-form-item label="员工头像">
            <ImageUpload ref="refUpload" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updateUserInfo">更新</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getBaseUserInfoApi } from '@/api/user'
import { saveUserDetailByIdApi } from '@/api/employees'
export default {
  name: 'EmployeesDetail',
  data() {
    return {
      userInfo: {
        timeOfEntry: '', // 入职时间
        username: '', // 姓名
        mobile: '', // 手机
        staffPhoto: ''// 头像
      },
      rules: {
        username: [
          { required: true, message: '用户名不可为空', trigger: 'blur' }
        ],
        timeOfEntry: [
          { required: true, message: '入职时间不可为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    userId() {
      return this.$route.params.id
    }
  },
  created() {
    this.getDetailUserInfo()
  },
  methods: {
    // 获取用户信息 进行回显
    async getDetailUserInfo() {
      const { data } = await getBaseUserInfoApi(this.userId)
      // console.log(data)
      this.userInfo = data
      this.$refs.refUpload.fileList = [{ url: data.staffPhoto }]
    },
    // 更新用户信息
    updateUserInfo() {
      this.$refs.userForm.validate(async valid => {
        if (!valid) return
        // 掉接口之前 应该获取一下上传的图片地址
        // let url = ''
        // if (this.$refs.refUpload.fileList.length>0) {
        //   url = this.$refs.refUpload.fileList[0].url
        // }
        const refUpload = this.$refs.refUpload
        if (!refUpload.isAllUpload) {
          this.$message.error('图片未上传成功，请稍后操作')
          return
        }
        const url = refUpload.fileList[0]?.url
        this.userInfo.staffPhoto = url || ''
        await saveUserDetailByIdApi(this.userInfo)
        this.$message.success('修改成功')
      })
    }
  }
}
</script>
